package com.tfswx.ruleengine.compute.gzjy.felfunc;

import com.greenpineyu.fel.context.FelContext;
import com.tfswx.ruleengine.compute.gzjy.BaseFn;
import com.tfswx.ruleengine.compute.util.DateUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DifferYMD extends BaseFn {

    private static final Pattern DATE_PATTERN = Pattern.compile("(\\d{4}-\\d{2}-\\d{2})");
    private static final Pattern DATE_CHINESE_PATTERN = Pattern.compile("(\\d{4}年\\d{1,2}月\\d{1,2}日)");

    @Override
    public Object call(Object[] arguments, FelContext context) {
        String dateStr = (String) arguments[0];
        String dateStr1 = (String) arguments[1];
        if (StringUtils.isBlank(dateStr) || StringUtils.isBlank(dateStr1)) {
            return "";
        } else {
            Date date = convertDate(dateStr);
            Date date1 = convertDate(dateStr1);
            if (date != null && date1 != null) {
                Calendar start = Calendar.getInstance();
                Calendar end = Calendar.getInstance();
                start.setTime(date);
                end.setTime(date1);
                int result = end.get(Calendar.MONTH) - start.get(Calendar.MONTH);
                int year = (end.get(Calendar.YEAR) - start.get(Calendar.YEAR));
                year = Math.abs(year);
                result = Math.abs(result);
                StringBuilder stringBuilder = new StringBuilder();
                if (year > 0) {
                    stringBuilder.append(year).append("年");
                }
                if (result > 0) {
                    stringBuilder.append(result).append("月");
                }
                return stringBuilder.toString();
            }
            return "";
        }
    }

    private Date convertDate(String data) {
        Matcher matcher = DATE_PATTERN.matcher(data);
        if (matcher.find()) {
            String dateStr = matcher.group(1);
            return DateUtil.parse(dateStr + " 00:00:00");
        }
        Matcher chineseMatcher = DATE_CHINESE_PATTERN.matcher(data);
        if (chineseMatcher.find()) {
            String dateStr = chineseMatcher.group(1);
            dateStr = dateStr.replace("年", "-")
                    .replace("月", "-")
                    .replace("日", "");
            return DateUtil.parse(dateStr + " 00:00:00");
        }
        return null;
    }

    @Override
    public String getZwmc() {
        return "日期相差月份";
    }

    @Override
    public boolean isExport() {
        return true;
    }

    @Override
    public List<Param> getParams() {
        List<Param> params = new ArrayList<>();
        params.add(new Param("startDate"));
        params.add(new Param("endDate"));
        return params;
    }

    @Override
    public String getName() {
        return "differYMD";
    }
}
